package com.ns;

import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import android.app.Activity;
import android.content.ComponentName;
import android.content.Intent;
import android.content.ServiceConnection;
import android.os.Bundle;
import android.os.IBinder;
import android.os.RemoteException;
import android.util.Log;
import android.view.View;
import android.widget.Button;

import com.demo.aidlinterface.IRemoteNSMessageService;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;

import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

public class MainActivity extends Activity implements ServiceConnection, View.OnClickListener {

        Button mBtnGetAidlState, mBtnAddEventBusMessage, mBtnReset;

        RecyclerView mRecyclerView;
        Adapter mAdapter;
        List<Item> mItems;
        Item mAIDLPerseveMessage;       // 本地持久化当前AIDL信息

        IRemoteNSMessageService remoteService;

        @Override
        protected void onCreate(Bundle savedInstanceState) {
                super.onCreate(savedInstanceState);
                setContentView(R.layout.activity_main);

                EventBus.getDefault().register(this);

                mBtnGetAidlState = findViewById(R.id.getAidlState);
                mBtnGetAidlState.setOnClickListener(this);
                mBtnGetAidlState.setEnabled(false);

                mBtnAddEventBusMessage = findViewById(R.id.addEventBusMessage);
                mBtnAddEventBusMessage.setOnClickListener(this);

                mRecyclerView = findViewById(R.id.recyclerView);
                LinearLayoutManager linearLayoutManager = new LinearLayoutManager(this);
                linearLayoutManager.setOrientation(RecyclerView.VERTICAL);
                mRecyclerView.setLayoutManager(linearLayoutManager);

                mItems = new ArrayList<>();
                mAdapter = new Adapter(this, mItems);
                mRecyclerView.setAdapter(mAdapter);

                mBtnReset = findViewById(R.id.reset);
                mBtnReset.setOnClickListener(this);
        }

        @Override
        protected void onResume() {
                super.onResume();
                Intent intent = new Intent();
                intent.setPackage("com.demo.aidlservice");
                intent.setAction("com.demo.aidlinterface.IRemoteNSMessageService");
                if (!super.bindService(intent, this, BIND_AUTO_CREATE)) {
                        Log.e("TAG", "绑定AIDL服务失败");
                }
        }

        @Override
        protected void onPause() {
                super.onPause();
                super.unbindService(this);
        }

        @Override
        protected void onDestroy() {
                super.onDestroy();
                EventBus.getDefault().unregister(this);
        }

        @Override
        public void onServiceConnected(ComponentName name, IBinder service) {
                this.remoteService = IRemoteNSMessageService.Stub.asInterface(service);
                mBtnGetAidlState.setEnabled(true);
        }

        @Override
        public void onServiceDisconnected(ComponentName name) {
                this.remoteService = null;
                mBtnGetAidlState.setEnabled(false);
        }

        @Override
        public void onClick(View v) {
                if (v.getId() == R.id.getAidlState) {
                        Log.d("TAG", "onClick");
                        try {
                                int curState = this.remoteService.receiveStateType();
                                Log.d("TAG", "curState: " + curState);

                                handleTopMessage(curState);
                                mAdapter.notifyDataSetChanged();

                        } catch (RemoteException e) {
                                e.printStackTrace();
                        }
                }

                if (v.getId() == R.id.addEventBusMessage) {

                        EventBusMessage message = new EventBusMessage();
                        message.setContent("EventBus消息: " + buildMessageContent());

                        EventBus.getDefault().post(message);
                }

                if (v.getId() == R.id.reset) {

                        mItems.clear();
                        mAdapter.notifyDataSetChanged();
                }

        }

        @Subscribe(threadMode = ThreadMode.MAIN)
        public void receiveEventBusMessage(EventBusMessage message) {
                Log.d("EventBus", message.getContent());

                Item item = new Item();
                item.setContent(message.getContent());
                item.setMessageType(Item.EVENTBUS);
                mItems.add(item);

                mAdapter.notifyDataSetChanged();
        }

        private void handleTopMessage(int messageState) {
                if (mItems.size() == 0) {
                        // 列表为空
                        mAIDLPerseveMessage = buildNewAidlMessage();
                        if(messageState == State.SHOW) {
                                mItems.add(0, mAIDLPerseveMessage);
                        }
                } else {
                        Item firstItem = mItems.get(0); //  取出第一条消息
                        if (firstItem.getMessageType() == Item.EVENTBUS) {
                                // 当前列表没有AIDL消息时
                                mAIDLPerseveMessage = buildNewAidlMessage();
                                if(messageState == State.SHOW) {
                                        mItems.add(0, mAIDLPerseveMessage);
                                }
                        } else {
                                if (messageState == State.HIDE) {
                                        // 判断AIDL消息状态, 当状态为隐藏时, 不显示第一条AIDL信息
                                        if(mItems.get(0).getMessageType()== Item.AIDL) {
                                                mAIDLPerseveMessage = mItems.get(0);
                                                mItems.remove(0);
                                        }
                                } else {
                                        // 当状态为显示时, 显示第一条
                                        if(mItems.get(0).getMessageType() == Item.AIDL) {
                                                // 更新消息内容
                                                mAIDLPerseveMessage = mItems.get(0);
                                                mAIDLPerseveMessage.setContent("AIDL消息: " + buildMessageContent());
                                        } else {
                                                mItems.add(0, mAIDLPerseveMessage);
                                        }
                                }
                        }
                }
        }

        private String buildMessageContent() {
                SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd hh:mm:ss");
                String dateString = simpleDateFormat.format(new Date());
                return dateString;
        }

        private Item buildNewAidlMessage() {
                Item topAidl = new Item();
                topAidl.setMessageType(Item.AIDL);
                topAidl.setMessageState(State.SHOW);
                topAidl.setContent("AIDL消息: " + buildMessageContent());
                return topAidl;
        }
}